package com.csthink.mr.groupby;

import com.csthink.mr.wordcount.WordCountDriver;
import com.csthink.mr.wordcount.WordCountMapper;
import com.csthink.mr.wordcount.WordCountReducer;
import com.csthink.utils.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * @description 需求: 从员工表文件中读取数据,根据部门编号分组统计，实现 select dept,count(1) cnt from emp group by dept;
 * @author <a href="mailto:csthink@icloud.com">Mars</a>
 * @since 2024-04-16 14:15
 */
public class GroupByApp {

    public static void main(String[] args) throws Exception {
        String input = "data/join/emp.txt";
        String output = "out";

        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf);
        job.setJobName("GroupByApp");

        FileUtils.deleteIfExists(conf, output);

        job.setJarByClass(GroupByApp.class);

        job.setMapperClass(MyMapper.class);
        job.setReducerClass(MyReducer.class);

        job.setOutputKeyClass(IntWritable.class);
        job.setOutputValueClass(IntWritable.class);

        FileInputFormat.setInputPaths(job, new Path(input));
        FileOutputFormat.setOutputPath(job, new Path(output));

        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }

    public static class MyMapper extends Mapper<LongWritable, Text, IntWritable, IntWritable> {

        public static final IntWritable ONE = new IntWritable(1);

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String[] splits = value.toString().split("\t");

            if (splits.length == 8) {
                context.write(new IntWritable(Integer.parseInt(splits[7])), ONE);
            }
        }
    }

    public static class MyReducer extends Reducer<IntWritable, IntWritable, IntWritable, IntWritable> {
        @Override
        protected void reduce(IntWritable key, Iterable<IntWritable> values, Reducer<IntWritable, IntWritable, IntWritable, IntWritable>.Context context) throws IOException, InterruptedException {
            int count = 0;
            for (IntWritable val : values) {
                count += val.get();
            }
            context.write(key, new IntWritable(count));
        }
    }
}
